package com.gmtx.syb.request;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import com.gmtx.syb.application.MyApplication;
import com.gmtx.syb.bean.HomePagePropBean;
import com.gmtx.syb.bean.IndexAdBean;
import com.gmtx.syb.utils.SystemUtil;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/11/3.
 */

public class RequestUtil {

    private static RequestUtil requestUtil;
    private Retrofit retrofit;
    public static final String TAG = "REQUEST";
    private Context context;

    private RequestUtil(Context context){
        this.context = context;
        initRetrofit();
    }

    //单例 初始化Retrofit
    public static RequestUtil getInstance(Context context){
        if(requestUtil == null){
            requestUtil = new RequestUtil(context);
        }
        return requestUtil;
    }
    
    private void initRetrofit(){
        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(35, TimeUnit.SECONDS)
                    .connectTimeout(35, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(RequestInfo.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
    }

    /**
     *--- 网络请求封装 ----
     * @param type Bean对像类型
     * @param map  请求参数
     * @param callback 请求回调  分别在:请求开始时,请求成功时,请求失败时进行回调
     * @param <T>
     */
    private <T> void doRequestGeneral(final Class<T> type, Map<String,String> map, final RequestCallback<T> callback){
        RequestServer requestServer = retrofit.create(RequestServer.class);
        Call<T> call = getCall(type,requestServer,map);
        if (call != null) {
            call.enqueue(new Callback<T>() {
                @Override
                public void onResponse(Call<T> call, Response<T> response) {
                    T data = response.body();
                    if (data != null) {
                        callback.onRequestSucceed(data);
                    }
                }
                @Override
                public void onFailure(Call<T> call, Throwable t) {
                    callback.onRequestFailed(t);
                }
            });
        }else{
            Log.e(TAG, "doRequest: 数据类型不正确");
        }
    }

    private <T> Call<T> getCall(Class type,RequestServer requestServer,Map<String,String> map){
        Call<T> call = null;
        if(type == IndexAdBean.class){
            call = (Call<T>) requestServer.getIndexAd(map);
        }else if(type == HomePagePropBean.class){
            call = (Call<T>) requestServer.getHomePageProp(map);
        }
        return call;
    }

    //对基础请求的封装
    public <T> void doRequest(final Class<T> type, Map<String,String> map, final RequestCallback<T> callback){
        doRequestGeneral(type,addArgsToMap(map),callback);
    }

    //添加系统级的请求参数
    private Map<String,String> addArgsToMap(Map<String,String> map){
        long currentTimeMillis = System.currentTimeMillis();
        map.put("d_model", android.os.Build.MODEL);//设备名称，品牌型号（三星note4，note5）
        map.put("d_brand", android.os.Build.MANUFACTURER);//设备模型,也就是手机品牌（三星，小米，华为）
        map.put("client", "android");//设备系统名称deviceSystemName
        map.put("os_version", android.os.Build.VERSION.RELEASE);//设备系统版本
        map.put("uuid", SystemUtil.IMEI(context));//设备ID
        map.put("screen", MyApplication.window_height + "" + "*" + MyApplication.window_width + "");//分辨率
        map.put("client_version", SystemUtil.getVersionName(context));//APP版本号
        map.put("build", SystemUtil.getVersionCode(context) + "");//app biuld 号
        map.put("st",  currentTimeMillis + "");//时间戳
        map.put("re", MyApplication.UMENG_CHANNEL);//发布渠道
        if (SystemUtil.isNetworkConnected(context)) {
            map.put("network_type", SystemUtil.checkNetworkState(context));//网络环境
        } else {
            map.put("network_type", "");//网络环境
        }
        map.put("sign", SystemUtil.MD5("spyg:%@" + currentTimeMillis + ""));//MD5加密串
        if(TextUtils.isEmpty(map.get("token"))){
            if (MyApplication.user.getToken() == null) {
                map.put("token", "");//上传token
            } else {
                map.put("token", MyApplication.user.getToken());//上传token
            }
            Log.d("时间戳", currentTimeMillis + "");
        }

        return map;
    }

    public interface RequestCallback<T>{
        void onRequestSucceed(T data);
        void onRequestFailed(Throwable t);
    }
}
